package leeon.mobile.server.bbscache;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import leeon.mobile.BBSBrowser.models.BlockObject;
import leeon.mobile.BBSBrowser.models.BoardObject;
import leeon.mobile.BBSBrowser.models.DocObject;

/**
 * 用作后台执行的方法
 * 每隔一定的时间收集缓存信息
 * @author leeon
 */
@SuppressWarnings("serial")
public class BbscacheServlet extends HttpServlet {
		
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String pathInfo = req.getPathInfo();
		if ("/refreshAll".equals(pathInfo)) {
			new BBSBoardService().refreshAll();
		} else if ("/refreshTotal".equals(pathInfo)) {
			new BBSBoardService().refreshTotal();
		} else if ("/refreshAllFromDb".equals(pathInfo)) {
			CacheService.getOrCreateAll(true);
		} else if ("/clearNewDocCache".equals(pathInfo)) {
			printCache(resp, CacheService.clearNewDocAllCache(true));
		} else if ("/clearIndexCache".equals(pathInfo)) {
			printCache(resp, CacheService.clearOffsetIndexAllCache(true));
		} else if ("/clearEntity".equals(pathInfo)) {
			new BBSCacheService().clearDoc();
		} else if ("/clearPicture".equals(pathInfo)) {
			new BBSUploadService().deleteAllPicture();
		} else if ("/printBoard".equals(pathInfo)) {
			printBoard(resp);
		} else if ("/printNewDocCache".equals(pathInfo)) {
			printCache(resp, CacheService.clearNewDocAllCache(false));
		} else if ("/printIndexCache".equals(pathInfo)) {
			printCache(resp, CacheService.clearOffsetIndexAllCache(false));
		} else if ("/test".equals(pathInfo)) {
			test(req, resp);
		}
	}
	
	private void printCache(HttpServletResponse resp, List<String> list) throws IOException {
		resp.setContentType("text/plain");
		resp.setCharacterEncoding("GB2312");
		
		PrintWriter w = resp.getWriter();
		w.print(list);
	}
	
	private void printBoard(HttpServletResponse resp) throws IOException {
		resp.setContentType("text/plain");
		resp.setCharacterEncoding("GB2312");
		
		PrintWriter w = resp.getWriter();
		List<BlockObject> all = CacheService.getOrCreateAll(false);
		List<DocObject> top = CacheService.getOrCreateTopTen(false, true);
		
		for (BlockObject block : all) {
			for (BoardObject b : block.getAllBoardList()) {
				w.println(b.getId()+":"+b.getName()+":"+b.getCh()+":"+b.getMaster()+":"+b.getTotal()+":"+b.getTotalG()+":"+b.getDocNumber()+":");
			}
		}
		
		for (DocObject doc : top) {
			w.println(doc.getId()+":"+doc.getAuthor()+":"+doc.getTitle()+":"+doc.getDate()+":"+doc.getDocNumber()+":"+doc.getBoard().getName()+":");
		}
	}
	
	private void test(HttpServletRequest req, HttpServletResponse resp) throws IOException {
//		PersistenceManager pm = PMF.get().getPersistenceManager();
//		try {
//		} finally {
//			pm.close();
//		}
	}
}
